#!/usr/local/bin/python

#generate db schema

import os, sys
import jinja2
import types
import time

SRC_PATH = './template/db/'
OUTPUT_PATH = '../db/'
SRC_SUFFIX = '.py'

sys.path.append(SRC_PATH)
from db_schema import *

g_db_desc = {}

#get all valid template file in SRC_PATH
def get_all_file():
	filelist = os.listdir(SRC_PATH)
	ret = []
	for f in filelist:
		name = f.split(SRC_SUFFIX)
		if len(name) == 2 and name[1] == '':
			ret += [ name[0], ]
		else:
			pass

	return ret

def error_msg(fname, pname, msg):
	print 'ERROR: %s: object_def: %s . %s' % (fname, pname, msg)


def output_lpc_schema():
	global g_db_desc
	fileloader = jinja2.FileSystemLoader('./template/')
	jinja_env = jinja2.Environment(loader = fileloader)
	tp = jinja_env.get_template('db_desc_lpc.tmpl')
	target = OUTPUT_PATH + 'pschema.c'
	
	mp = {} 
	for k,v in g_db_desc.items():
		mp[k] = {}
		mp[k]['__key'] = v.get('__key', '')
		mp[k]['__idx'] = v.get('__idx', '')
		mp[k]['field'] = {}
		for fk,p in v.items():
			if len(fk) > 2 and fk[:2] == "__": continue
			mp[k]['field'][fk] = p['ftype']

	tp.stream(dbs=mp,date=time.ctime(),objs=g_db_desc.keys()).dump(target)	
	print 'generate ok......'


#gen db structure
#desc: data field define
def gen_db_struct(fname, obj_name, key, desc):
	global g_db_desc
	vdata = {'__key':key}
	key_list = []
	#check validate
	for k,v in desc.iteritems():
		p = {}
		if type(v) == types.ListType:
			vtype = v[0]
		else:
			vtype = v	

		if vtype == INT:
			p['ftype'] = 'int'
			key_list.append(k)
		elif vtype == STR:
			p['ftype'] = 'str'
			key_list.append(k)
		
		vdata[k] = p

	#set index if exist	
	vdata['__idx'] = desc.get('index', '')
	g_db_desc[obj_name] = vdata

def generate_db(fname):
	m = __import__(fname)
	for pname, desc in m.__dict__.iteritems():
		if not type(desc) == types.DictType:
			continue
		if len(pname) > 2 and pname[:2] == "__":
			continue

		if not desc.has_key('data'):
			print error_msg(fname, pname, 'no data define')
			continue
		
		gen_db_struct(fname, pname, desc.get('key', ''), desc['data'])
	
	output_lpc_schema()
	

	
if __name__ == '__main__':
	all_file = get_all_file()
	for f in all_file:
		generate_db(f)
